using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

//using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Management.Smo;

namespace Serialcoder.Erp.Tools.PatchCreator
{
	public partial class DatabaseExplorer : UserControl
	{
		public DatabaseExplorer()
		{
			InitializeComponent();
		}

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			if (!DesignMode)
			{
				RefreshServerView();
			}			
		}

		public void RefreshServerView()
		{
			treeView1.Nodes.Clear();
			TreeNode node = new TreeNode("Chargement...");
			treeView1.Nodes.Add(node);
			backgroundWorker1.RunWorkerAsync();
		}

		private Server InitialiseServer()
        {
			Server serv = new Server(new Microsoft.SqlServer.Management.Common.ServerConnection("172.16.50.1", "sa", "0TfGwO3hmo6F5xveQTLX"));

			try
            {
                // set the default properties we want upon partial instantiation - smo is *really* slow if you don't do this
                serv.SetDefaultInitFields(typeof(Table), "IsSystemObject", "CreateDate");
                serv.SetDefaultInitFields(typeof(StoredProcedure), "IsSystemObject", "CreateDate");
                serv.SetDefaultInitFields(typeof(UserDefinedFunction), "IsSystemObject", "CreateDate", "FunctionType");
                serv.SetDefaultInitFields(typeof(Microsoft.SqlServer.Management.Smo.View), "IsSystemObject", "CreateDate");
                serv.SetDefaultInitFields(typeof(Column), "Identity");
                serv.SetDefaultInitFields(typeof(Index), "IndexKeyType");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return null;
            }
			//cb.Items.Clear();
			//foreach (Database db in serv.Databases)
			//{
			//    if (!db.IsSystemObject)
			//    {
			//        cb.Items.Add(db.Name);
			//    }
			//}
			//cb.Enabled = true;
            return serv;
        }

		private Boolean IsSystemObject(SqlSmoObject smoObject)
		{
			if (smoObject is Table) return ((Table)smoObject).IsSystemObject;
			if (smoObject is StoredProcedure) return ((StoredProcedure)smoObject).IsSystemObject;
			if (smoObject is UserDefinedFunction) return ((UserDefinedFunction)smoObject).IsSystemObject;
			if (smoObject is Microsoft.SqlServer.Management.Smo.View) return ((Microsoft.SqlServer.Management.Smo.View)smoObject).IsSystemObject;
			if (smoObject is Database) return ((Database)smoObject).IsSystemObject;
			throw new ApplicationException("Unrecognised object type - " + smoObject.ToString());
		}

		private void treeView1_DoubleClick(object sender, EventArgs e)
		{			
			if (treeView1.SelectedNode != null && treeView1.SelectedNode.Tag != null && treeView1.SelectedNode.Tag is SqlSmoObject)
			{
				SqlSmoObject obj = treeView1.SelectedNode.Tag as SqlSmoObject;

				if (obj is Table)
				{
					//if (MainForm.Current.ActiveMdiChild != null)
					{
						System.Collections.Specialized.StringCollection col = (obj as Table).Script();
						StringBuilder sql = new StringBuilder();
						foreach (String s in col)
						{
							sql.AppendLine(s);
						}
						Context.Current.CreatePatch(sql.ToString());
					}					
				}
			}
		}

		private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
		{
			Server server = InitialiseServer();

			TreeNode node = new TreeNode("Databases");


			foreach (Database database in server.Databases)
			{
				if (!IsSystemObject(database))
				{
					TreeNode serverNode = new TreeNode(database.Name);
					serverNode.Tag = database;


					TreeNode tablesNode = new TreeNode("Tables");
					foreach (Table table in database.Tables)
					{
						TreeNode tableNode = new TreeNode(table.Name);
						tableNode.Tag = table;
						tablesNode.Nodes.Add(tableNode);
					}
					serverNode.Nodes.Add(tablesNode);


					TreeNode viewsNode = new TreeNode("Views");
					foreach (Microsoft.SqlServer.Management.Smo.View view in database.Views)
					{
						TreeNode viewNode = new TreeNode(view.Name);
						viewNode.Tag = view;
						viewsNode.Nodes.Add(viewNode);
					}
					serverNode.Nodes.Add(viewsNode);


					TreeNode proceduresNode = new TreeNode("Stored procedures");
					foreach (Microsoft.SqlServer.Management.Smo.StoredProcedure procedure in database.StoredProcedures)
					{
						TreeNode procedureNode = new TreeNode(procedure.Name);
						proceduresNode.Nodes.Add(procedureNode);
					}
					serverNode.Nodes.Add(proceduresNode);

					node.Nodes.Add(serverNode);
				}


			}
			e.Result = node;
			
		}

		private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			treeView1.Nodes.Clear();
			treeView1.Nodes.Add(e.Result as TreeNode);
			treeView1.TopNode.Expand();
		}

	}
}
